
<template>
  <div class="login-container">
    <!-- 动态粒子背景 -->
    <vue-particles color="#fff" class="particles"/>
    <div class="glass-card">
      <div class="branding" v-if="!qrCodeSrc">
        <img src="@/assets/logo.png" class="logo" alt="桌游星球">
        <h1>欢迎来到快玩桌游 🌌</h1>
      </div>
      <el-form class="auth-form">
        <!-- 表单项增加图标 -->
        <el-form-item prop="username" v-if="loginType === 'password' && !qrCodeSrc">
          <el-input v-model="form.username" placeholder="用户名">
            <template #prefix>
              <el-icon><User/></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password" v-if="loginType === 'password' && !qrCodeSrc">
          <el-input v-model="form.password" type="password" placeholder="密码" >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 手机号登录 -->
        <div v-else-if="!qrCodeSrc">
          <el-form-item prop="phone">
            <el-input v-model="form.phone" placeholder="手机号" >
              <template #prefix>
                <el-icon><Iphone /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="captcha">
            <el-input v-model="form.captcha" placeholder="验证码">
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
              <template #append>
                <el-button type="success"
                    :disabled="isDisabled"
                    @click="handleGetCode"
                    class="get-code-button"
                >
                  {{ isDisabled ? countdown : '获取验证码' }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </div>
        <div class="switch-type" v-if="!qrCodeSrc">
        <div @click="toggleLoginType" style="margin-bottom: 20px">
          {{ loginType === 'password' ? '手机验证码登录' : '密码登录' }}
        </div>
        </div>
        <div class="divider" v-if="!qrCodeSrc"><span>其他登录方式</span></div>
        <!--   微信登录-->
        <el-tooltip content="微信登录" placement="top" v-if="!qrCodeSrc">
          <div class="wechat-login-btn" @click="handleWechatLogin" style="margin-bottom: 30px">
            <svg-icon name="wechat" class="wechat-icon" />
          </div>
        </el-tooltip>
        <div  v-if="qrCodeSrc" style="padding-left: 210px;padding-bottom: 30px">
          <el-button type="info" size="large" style="background-color: transparent; border: none;color:black;font-size: 30px;font-weight: 700;"
          @click="reSetQrCodeSrc">
            <el-icon><Switch /></el-icon>返回
          </el-button>
          </div>
        <img v-if="qrCodeSrc"  style="width: 400px;height: 400px" :src="qrCodeSrc" alt="WeChat Login QR Code" />

        <el-button  v-if="!qrCodeSrc"
            class="login-btn"
            @click="handleLogin"
            :loading="loading"
        >
          <span v-if="!loading">开启桌游之旅 🎲</span>
        </el-button>
      </el-form>

    </div>
  </div>
</template>

<style scoped>

.get-code-button {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.get-code-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.login-container {
  height: 100vh;
  background: linear-gradient(45deg, #2c3e50, #3498db);
  position: relative;
}

.particles {
  position: absolute;
  width: 100%;
  height: 100%;
}

.glass-card {
  position: relative;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 2rem;
  width: 450px;
  height: 550px;
  margin: 0 auto;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.branding {
  text-align: center;
  margin-bottom: 2rem;

  .logo {
    width: 120px;
    filter: drop-shadow(0 4px 6px rgba(0,0,0,0.1));
  }

  h1 {
    color: white;
    font-size: 1.8rem;
    margin: 1rem 0;
    text-shadow: 0 2px 4px rgba(0,0,0,0.2);
  }
}

.auth-form {
  ::v-deep .el-input__inner {
    background: rgba(255,255,255,0.8);
    border: none;
    border-radius: 10px;
    height: 45px;
  }
}

.login-btn {
  width: 100%;
  height: 45px;
  background: linear-gradient(45deg, #e74c3c, #e67e22);
  border: none;
  color: white;
  font-weight: bold;
  border-radius: 10px;
  transition: transform 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(231, 76, 60, 0.3);
  }
}

img {
  max-width: 100%;
  height: auto;
}


.divider {
  display: flex;
  align-items: center;
  margin: 1rem 0;

  &::before,
  &::after {
    content: "";
    flex: 1;
    border-bottom: 1px solid rgba(255,255,255,0.3);
  }

  span {
    padding: 0 1rem;
    font-size: 0.9rem;
  }
}

.wechat-login-btn {
  width: 50px;
  height: 50px;
  background: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: transform 0.3s;
  margin: 0 auto;

  &:hover {
    transform: scale(1.1);
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
  }
}

.wechat-icon {
  width: 130px;
  height: 130px;
  color: #2aae67;
}


@keyframes float {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-20px); }
}
</style>

<script setup>
import { ref} from 'vue'
import {ElMessage} from "element-plus";
import axios from "axios";
import { User,Lock,Iphone,Switch} from '@element-plus/icons-vue';
import router from "@/router";

const countdown = ref(60); // 倒计时时间（秒）
const isDisabled = ref(false);
let timer;

const startCountdown = () => {
  if (timer) clearInterval(timer); // 如果计时器已存在，先清除
  isDisabled.value = true;
  timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
      countdown.value = 60;
      isDisabled.value = false;
    }
  }, 1000);
};

const handleGetCode = () => {
  axios.get(BASE_URL+'/v1/user/captcha/generate/' + form.value.phone)
      .then(response => {
        // 检查服务器返回的数据是否符合预期
        if (response.data.code === 2000) {
          ElMessage.success('验证码已发送');
          startCountdown();
        } else {
          ElMessage.error('服务器返回错误信息: ' + response.data.message || '未知错误');
        }
      })
      .catch(error => {
        ElMessage.error(error.response?.data?.message || '获取验证码失败');
      });
};

const loading = ref(false)

const loginType = ref('password')
const form = ref({
  username: '',
  password: '',
  phone: '',
  captcha: ''
})

const toggleLoginType = () => {
  loginType.value = loginType.value === 'password' ? 'phone' : 'password'
}

const handleLogin = async () => {
  try {
    let res
    if (loginType.value === 'password') {
      await axios.post(BASE_URL + '/v1/user/login', form.value)
          .then((response) => {
            // console.log(response.data);
            if (response.data.code === 2000) {
              // console.log(response);
              localStorage.setItem('user', JSON.stringify(response.data.data));
              localStorage.setItem('jwtToken', response.headers['authorization'].split(' ')[1]);
              ElMessage.success('登录成功！');
              router.push('/');
            } else {
              ElMessage.error(response.data.msg);
              form.value = {
                username: '',
                password: '',
                phone: '',
                captcha: ''};
            }
          });
    } else {
      await axios.post(BASE_URL + '/v1/user/login/phone', form.value)
          .then((response) => {
            // console.log(response.data);
            if (response.data.code === 2000) {
              // console.log(response);
              localStorage.setItem('user', JSON.stringify(response.data.data));
              localStorage.setItem('jwtToken', response.headers['authorization'].split(' ')[1]);
              ElMessage.success('登录成功！');
              router.push('/');
            } else {
              ElMessage.error(response.data.msg);
              form.value = {
                username: '',
                password: '',
                phone: '',
                captcha: ''};
            }
          });
    }
    if (res.data.code === 2000) {
        console.log(res.data.data)
    }
  } catch (error) {

  }
}


const qrCodeSrc = ref(null);

async function handleWechatLogin() {
  try {
    // 获取二维码和state
    const { data } = await axios.get(BASE_URL+'/v1/user/api/wechat/getQrCode');
    qrCodeSrc.value = `data:image/png;base64,${data.qrCode}`;

    // 开始轮询
    startPolling(data.state);
  } catch (error) {
    ElMessage.error('获取二维码失败');
  }
}



function startPolling(state) {
  const poller = setInterval(async () => {
    try {
      const { data } = await axios.get(BASE_URL+'/v1/user/api/wechat/check-login', {
        params: { state }
      });

      if (data.loggedIn) {
        clearInterval(poller);
        // localStorage.setItem('token', data.token);
        //登录成功，发送请求获取用户信息
        await getUserInfoByWxOpenId(data.token);
        setTimeout(() => {
          router.push('/');
        },2000);
      }
    } catch (error) {
      clearInterval(poller);
      ElMessage.error('登录状态检查失败');
    }
  }, 2000); // 每2秒检查一次
}

const getUserInfoByWxOpenId =async (token) => {
    const { data } =await axios.get(BASE_URL+'/v1/user/api/wechat/getUserInfoByWxOpenId?token='+token);
    console.log(data.data);
    if (data.code === 2000) {
      console.log(data.data);
      localStorage.setItem('user', JSON.stringify(data.data));
      localStorage.setItem('jwtToken', data.token);
      ElMessage.success('登录成功！');
    } else {
      ElMessage.error(data.msg);
    }
}

const reSetQrCodeSrc = () => {
  qrCodeSrc.value = null;
}
</script>